package com.Xsoft.ShoppingList;

import java.util.List;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.LinearLayout;
import android.widget.TextView;

public class ProductArrayAdapter extends ArrayAdapter<Product> {
	private int resource;
	private int checkedItemsNum = 0;

	public ProductArrayAdapter(Context _context, int _resource,
			List<Product> _objects) {
		super(_context, _resource, _objects);
		this.resource = _resource;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		final Product product = getItem(position);
		LinearLayout productView;
		String productName = product.getName();
		if (convertView == null) {
			productView = new LinearLayout(getContext());
			String inflater = Context.LAYOUT_INFLATER_SERVICE;
			LayoutInflater vi = (LayoutInflater) getContext().getSystemService(
					inflater);

			vi.inflate(resource, productView, true);
		} else {
			productView = (LinearLayout) convertView;
		}
		TextView nameView = (TextView) productView
				.findViewById(R.id.texViewName);
		CheckBox isBought = (CheckBox) productView
				.findViewById(R.id.checkBoxBought);
		if (product.isBought()) {
			checkedItemsNum++;
			isBought.setChecked(true);
		} else {
			if (checkedItemsNum > 0) {
				checkedItemsNum--;
			}
			isBought.setChecked(false);
		}
		isBought.setOnCheckedChangeListener(new OnCheckedChangeListener() {

			@Override
			public void onCheckedChanged(CompoundButton buttonView,
					boolean isChecked) {
				product.setBought(isChecked);
				if (isChecked) {
					checkedItemsNum++;
				} else {
					if (checkedItemsNum > 0) {
						checkedItemsNum--;
					}
				}
			}
		});
		nameView.setText(productName);
		return productView;
	}

	public int getCheckedItemsNum() {
		return checkedItemsNum;
	}

}
